#include "lua.h"
#include "lauxlib.h"
#include "cm_ntp.h"
#include "lua_test_entry.h"
#include <string.h>
#include <stdlib.h>

int ntp_callback_ref = LUA_NOREF;

// --- C Callback for NTP events ---
static void ntp_event_callback(cm_ntp_event_e event_id, void *event_param, void *cb_param)
{
    lua_event_t event;
    event.id = LUA_EVENT_NTP_SYNC_RESULT;

    // We need to pass both the status and the time string (if available)
    // We can use a small struct for that
    ntp_result_t *result = (ntp_result_t*)malloc(sizeof(ntp_result_t));
    if (!result) return;

    if (event_id == CM_NTP_EVENT_SYNC_OK) {
        result->is_ok = 1;
        result->time_str = strdup((const char*)event_param);
    } else {
        result->is_ok = 0;
        result->time_str = NULL;
    }

    event.data.pval = result;
    lua_event_post(&event);
}

// Lua: ntp.sync(server, port, callback)
static int l_ntp_sync(lua_State *L)
{
    // Get arguments
    const char *server = luaL_optstring(L, 1, NULL);
    int port = luaL_optinteger(L, 2, 123);
    luaL_checktype(L, 3, LUA_TFUNCTION);

    // Unref any previous callback
    if (ntp_callback_ref != LUA_NOREF) {
        luaL_unref(L, LUA_REGISTRYINDEX, ntp_callback_ref);
    }

    // Store the new callback
    lua_pushvalue(L, 3);
    ntp_callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);

    // Set NTP server if provided
    if (server) {
        cm_ntp_set_cfg(CM_NTP_CFG_SERVER, (void*)server);
    }

    // Set NTP port
    uint16_t u16_port = port;
    cm_ntp_set_cfg(CM_NTP_CFG_PORT, &u16_port);

    // Set our C callback
    cm_ntp_set_cfg(CM_NTP_CFG_CB, ntp_event_callback);

    // Start the sync process
    int ret = cm_ntp_sync();

    lua_pushboolean(L, ret == 0);
    return 1;
}

static const luaL_Reg ntp_lib[] = {
    {"sync", l_ntp_sync},
    {NULL, NULL}
};

int luaopen_ntp(lua_State *L)
{
    luaL_newlib(L, ntp_lib);
    return 1;
}
